var _pagination = null;
//缓存 response
var _cache = null;
var _html = '';
var _imageUrl = '';
var _sendflag = false;
$(function() {

	$('.doubledate').kuiDate({
		className : 'doubledate',
		isDisabled : "0"
	});

	// 图片选择器 初始化
	browse('uploadImage', 'image', 96, 96);
	$("input[type='file']").change(function() {
		$(this).prev().prev().val($(this).val());
	});

	$('.doubledate').kuiDate({
		className : 'doubledate',
		isDisabled : "0" // isDisabled为可选参数，“0”表示今日之前不可选，“1”标志今日之前可选
	});
	qmsk.initSelect({
		url : '../messageType/list/0/100',
		id : "searchType",
		heads : ["typeId", "typeName"],
		defaults : {
			key : '全部',
			value : ' '
		}
	});
	qmsk.initSelect({
		url : '../messageType/list/0/100',
		id : "addType",
		heads : ["typeId", "typeName"]
	});
	initImage();

	initShopSelecter();
});

/**
 * 初始化店面选择器
 */
function initShopSelecter() {
	refreshInput($(".serWrapper"));
	$("#shopIsChoosed").removeAttr("checked");
	$("#shopName").attr("disabled", "disabled");

	$("#shopIsChoosed").bind("click", function() {
		var checked = $(this).attr("checked");
		if (checked) {
			$("#shopName").removeAttr("disabled");
		} else {
			$("#shopName").attr("disabled", "disabled");
			$("#shopName").empty();
		}
	});
}

/**
 * 栏目选择器
 */
function columnSelecter(self) {
	$(self).blur();
	initSelecter({
		method : 'get',
		url : '../column/selecter',
		heads : ["columnId", "columnName"],
		titles : ["栏目Id", "栏目名称"],
		zindex : 500,
		callBack : function(response, row) {
			var value = response.getValue('columnId', row);
			var key = response.getValue('columnName', row);
			var option = $("<option value='" + value + "'>" + key + "</option>");
			$(self).empty().append($(option));
		}
	});
}

//初始化图片查看组件
function initImage() {
	Shadowbox.init();
	window.openImage = function(url) {
		Shadowbox.open({
			content : url,
			player : 'img'
		});
	};
}

/**
 * 打开添加面板
 */
function openAddPanel() {
	_html = '';
	editorHtml = '';
	$("#addPanel input[type='text']").val('');
	$("#addPanel input[type='file']").val('');
	$("#addPanel textarea").val('');
	$("span#addImage > img").attr('src', "../images/img_activities1.jpg");

	$("#addOrUpdate").unbind("click");
	$("#addOrUpdate").bind("click", add);

	$("#addPanel").show();
	$("#yinying1").show();
	addMargin($("#addPanel"));
}

/*** 关闭添加面板
 */
function closeAddPanel() {
	$("#addPanel").hide();
	$("#yinying1").hide();
}

/**
 * 添加层 店面选择器
 */
function selectAddShop() {
	initSelecter({
		method : 'post',
		url : '../shop/find/shopList',
		heads : ["id", "name", "mp"],
		titles : ["店面ID", "店面名称", "电话"],
		zindex : 500, //缺省值
		callBack : callBack
	});

	function callBack(response, row) {
		var name = response.getValue('name', row);
		var shopId = response.getValue("id", row);
		$("#addShopName").val(name);
		$("#shopId").val(shopId);
	}

}

function search() {

	var status = $("#search_status").val();

	_pagination = new Pagination({
		url : '../massmessage/list',
		data : {
			status : status
		},
		success : printListToPage,
		pagerHandler : 'pager'
	});
}

function printListToPage(rst) {
	var response = new qmsk.Response(rst);
	_cache = response;
	qmsk.dataTable({
		tbodyId : 'messageList',

		heads : ["titile", "author", "digest", "imagePath", "orderId", "url", "createFileTime", "status", "id"],
		response : response,
		sup : ['sup', '共 [index] 条'],
		handler : [[3, imageHandler], [5, urlHandler], [8, updateDeleteButton]]
	});
}

function dateHandler(date, row) {
	if (qmsk.isEmpty(date)) {
		return '';
	}
	return date.toString().substring(0, 10);
}

function del(messageId) {
	artConfirm('确定删除该条信息吗？', function() {
		qmsk.post('../massmessage/delete/' + messageId, function(respones) {
			artSuccess("删除成功！");
			_pagination.reload();
		});
	});

}

function updateDeleteButton(messageId, row) {
	//"<input type='button' class='common_btn' value='修改' onclick=\"preUpdate(" + messageId + "," + row + ")\">" +
	var del = "<input type='button' class='common_btn del' value='删除' onclick=\"del(" + messageId + "," + row + ")\">";
	var view = "<input type='button' class='common_btn del' value='预览' onclick=\"toView(" + messageId + "," + row + ")\">";
	return del + view;
}

function toView(id) {
	window.open('veiwmassmsg.htm?id=' + id, 'height=500,width=400,top=200,left=200,toolbar=no,menubar=no,scrollbars=yes, resizable=no,location=no, status=no');
}

function urlHandler(url, row) {
	return "<a href='#' style='text-decoration:underline; color: green;' onclick=\"openUrl('" + url + "')\">预览</a>";
}

function openUrl(url) {
	window.open(url, '预览链接', 'height=500,width=400,top=200,left=200,toolbar=no,menubar=no,scrollbars=yes, resizable=no,location=no, status=no');
}

function imageHandler(url, row) {
	return "<a href='#' style='text-decoration:underline; color: green;' onclick=\"openImage('" + url + "')\">预览</a>";
}

function send() {
	if (_sendflag) {
		artAlert("您已经发送一次，如果确实需要发送第二次请刷新页面！");
		return;
	}
	_sendflag = true;
	artConfirm("确定发送吗？", function() {
		qmsk.post('../massmessage/send', function(response) {
			var failed = response.getValue("failed");
			var success = response.getValue("success");

			artSuccess("成功：" + success + "，失败：" + failed);
			_pagination.reload();

		});
	});
}

function add() {

	var shopId = $("#shopId").val();
	var title = $("#title").val();
	var author = $("#author").val();
	var url = $("#url").val();
	var orderId = $("#orderId").val();
	var digest = $("#digest").val();
	var status = $("#status").val();
	var url = getHtmlUrl(editorHtml);
	var content = getHtmlFromUrl(url);
	content = HTMLEnCode(content);
	if (qmsk.isEmpty(orderId)) {
		orderNums = 0;
	}
	var data = {
		shopId : shopId,
		title : title,
		author : author,
		url : url,
		orderId : orderId,
		digest : digest,
		status : status,
		content : content
	};
	var data = qmsk.cleanObject(data);

	$.ajaxFileUpload({
		url : "../massmessage/insert",
		secureuri : false,
		data : data,
		fileElementId : "uploadImage",
		dataType : "json",
		type : "post",
		success : function(rst, status) {
			if (qmsk.isEmpty(rst)) {
				artError('服务器忙，请联系系统管理员！');
				return;
			}
			if ( typeof rst === "string") {
				rst = JSON.parse(rst);
			}
			var response = new qmsk.Response(rst);

			if (response.state === 0) {
				closeAddPanel();
				artSuccess("添加成功！");
				_pagination.reload();
			} else if (response.state == 1) {
				artError(response.msg);
			} else {
				checkStateShowErrorMsgAndDealResult(JSON.stringify(rst));
			}
		}
	});
	console.log(JSON.stringify(data));
}

function getHtmlFromUrl(url) {
	var response = qmsk.asynGet('../htmlUtils/find/loadHtml', {
		'htmlUrl' : url
	});
	var html = response.getValue("htmlStr");
	return html;
}

function generateHtml() {
	var url = $("#Url").val();
	if (qmsk.isNotEmpty(html)) {
		url = getHtmlUrl(html);
	}

}

function getHtmlUrl(html) {
	var url = '';
	$.ajax({
		type : "post",
		async : false,
		datatype : "JSON",
		url : "../htmlUtils/htmlFileGender",
		data : {
			'html' : html
		},
		success : function(rst) {
			if ( typeof rst === "string") {
				rst = JSON.parse(rst);
			}
			var response = new qmsk.Response(rst);
			url = response.getValue("url");
		}
	});
	return url;
}

function HTMLEnCode(str) {
	var s = "";
	if (str.length == 0)
		return "";
	s = str.replace(/&/g, "&gt;");
	s = s.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	s = s.replace(/    /g, "&nbsp;");
	s = s.replace(/\'/g, "'");
	s = s.replace(/\"/g, "&quot;");
	s = s.replace(/\n/g, "<br>");
	return s;
}

function HTMLDeCode(str) {
	var s = "";
	if (str.length == 0)
		return "";
	s = str.replace(/&gt;/g, "&");
	s = s.replace(/&lt;/g, "<");
	s = s.replace(/&gt;/g, ">");
	s = s.replace(/&nbsp;/g, "    ");
	s = s.replace(/'/g, "\'");
	s = s.replace(/&quot;/g, "\"");
	s = s.replace(/<br>/g, "\n");
	return s;
}

function generateHtmlUrl() {
	var html = editorHtml;
	console.log("html:" + html);
	console.log("_html:" + _html);
	if (_html == html) {
		return;
	}
	var url = '';
	if (qmsk.isNotEmpty(html)) {
		url = getHtmlUrl(html);
	}
	$("#Url").val(qmsk.isEmpty(url) ? '' : url);
}
